import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Plus, ChevronUp, ChevronDown } from "lucide-react";
import { insertProxyRuleSchema } from "@shared/schema";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";

const formSchema = insertProxyRuleSchema.extend({
  type: z.enum(["HTTP", "HTTPS", "TCP", "UDP"]),
});

type FormData = z.infer<typeof formSchema>;

export function QuickConfigForm() {
  const [isExpanded, setIsExpanded] = useState(true);
  const { toast } = useToast();

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      description: "",
      type: "HTTP",
      localPort: 8080,
      remotePort: 80,
      targetHost: "localhost",
      status: "stopped",
      loadBalancing: "round-robin",
      healthCheck: true,
    },
  });

  const createProxyMutation = useMutation({
    mutationFn: (data: FormData) => apiRequest("POST", "/api/proxy-rules", data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理规则创建成功" });
      reset();
    },
    onError: () => {
      toast({ title: "创建失败", variant: "destructive" });
    },
  });

  const onSubmit = (data: FormData) => {
    createProxyMutation.mutate(data);
  };

  const handleReset = () => {
    reset();
  };

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-lg font-semibold text-slate-800">快速配置</CardTitle>
            <p className="text-slate-600 text-sm">快速添加新的代理规则</p>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setIsExpanded(!isExpanded)}
          >
            {isExpanded ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
          </Button>
        </div>
      </CardHeader>
      
      {isExpanded && (
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="space-y-2">
                <Label htmlFor="name">规则名称</Label>
                <Input
                  id="name"
                  placeholder="例如: my-app"
                  {...register("name")}
                />
                {errors.name && (
                  <p className="text-sm text-red-600">{errors.name.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="type">协议类型</Label>
                <Select 
                  value={watch("type")} 
                  onValueChange={(value) => setValue("type", value as "HTTP" | "HTTPS" | "TCP" | "UDP")}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="HTTP">HTTP</SelectItem>
                    <SelectItem value="HTTPS">HTTPS</SelectItem>
                    <SelectItem value="TCP">TCP</SelectItem>
                    <SelectItem value="UDP">UDP</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="localPort">本地端口</Label>
                <Input
                  id="localPort"
                  type="number"
                  placeholder="8080"
                  {...register("localPort", { valueAsNumber: true })}
                />
                {errors.localPort && (
                  <p className="text-sm text-red-600">{errors.localPort.message}</p>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="remotePort">远程端口</Label>
                <Input
                  id="remotePort"
                  type="number"
                  placeholder="80"
                  {...register("remotePort", { valueAsNumber: true })}
                />
                {errors.remotePort && (
                  <p className="text-sm text-red-600">{errors.remotePort.message}</p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="targetHost">目标主机</Label>
                <Input
                  id="targetHost"
                  placeholder="localhost"
                  {...register("targetHost")}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">描述（可选）</Label>
                <Input
                  id="description"
                  placeholder="服务描述"
                  {...register("description")}
                />
              </div>
            </div>

            <div className="flex items-center justify-end space-x-4">
              <Button type="button" variant="outline" onClick={handleReset}>
                重置
              </Button>
              <Button 
                type="submit" 
                disabled={createProxyMutation.isPending}
                className="bg-primary hover:bg-blue-700"
              >
                <Plus className="w-4 h-4 mr-2" />
                创建代理
              </Button>
            </div>
          </form>
        </CardContent>
      )}
    </Card>
  );
}
